define (require, exports, module) ->
  # 引入样式
  require 'mods/prod_detail/prod_detail_css.css'
  # 引入API服务
  product_detail_api = require 'mods/prod_detail/prod_detail_api'

  # 固定头部组件
  {fixedTop, fixedDestroy} = require 'js/fix_top.js'

  module.exports = Vue.extend

    template: require 'mods/prod_detail/prod_detail_tpl.js'

    data: () ->
      # 是否加载完成
      loadedSucc: false
      # 加载失败提示语
      loadedFail: ''
      # tab导航
      tabNav: ['产品详情', '产品净值', '产品公告', '法律文件']
      # 当前的tab菜单
      tabNavSta: 0
      # td的宽度
      tdWArr:[]
      # tab菜单ul的宽度
      tabUlWidth: 0
      # 屏幕的宽度
      screenWidth: document.body.clientWidth
      # 优化 因为频繁触发resize函数，导致页面很卡的问题
      timer: false
      # 产品详情信息
      product_xq: []
      prodInfo: {}
      # 是否可购买
      p_can_buy: true
      # 产品净值
      prodNet: []
      # 公告列表数组
      notices: []
      # 法律文件
      prodLaw: []
      # 控制法律文件数据的显示与否
      isShowLaw: false
      # 控制公告数据的显示与否
      isShowNotice: false
      # 控制净值数据的显示与否
      isShowNet: false
      # 点击查看更多-产品净值
      viewMoreNet: '查看更多'
      # 点击查看更多-产品公告
      viewMoreNotice: '查看更多'
      # 点击查看更多-法律文件
      viewMoreLaw: '查看更多'
      # 当前页码--产品净值
      pageNet: 1
      # 当前页码--产品公告
      pageNotice: 1
      # 当前页码--法律文件
      pageLaw: 1
      # 委托金额
      entrust_balance: ''
      # 页面显示内容 0产品详情；1登录；2未做风险测评；3产品风险高于用户风险；4风险测评都匹配，承诺书未签署时提示
      visitProdType: 0
      # 风险等级是否匹配
      isShowRisk: false
      # 是否提示投资期限
      isShowTzqx: false
      # 是否提示投资品种
      isShowTzpz: false
      # 用户信息
      userInfo: {}
      # 用于风险等级匹配的产品信息
      prodObj: {}

    # 方法
    methods:

      # 插件加载
      pluginLoad: () ->
        self = @

      # 加载成功
      loadedSuccFunc: () ->
        self = @
        self.$nextTick () ->
          # 加载成功标识
          self.loadedSucc = true
          # 插件加载
          self.pluginLoad()

      # 分页 type: 0净值；1产品公告；2法律文件
      gotoPage: (code, page, type) ->
        self = @
        if 0 is type
          self.pageNet = parseInt page
          self.getNetList(code)
        else if 1 is type
          self.pageNotice = parseInt page
          self.getNoticeList(code)
        else if 2 is type
          self.pageLaw = parseInt page
          self.getLawList(code)

      # 风险测评
      doRiskExam: (type) ->
        self = @

        if '1' is '' + type
          self.$router.push {path: '/risk'}
        else if '2' is '' + type
          self.$router.push {path: '/'}

      # 产品披露是否满足
      prodInfoShow: (userInfo, prodObj) ->
        self = @

        # 风险等级是否匹配的处理
        if 'false' is '' + prodObj?.fxpp
          if '' + userInfo?.risk_level < prodObj?.risk_level
            if '0' is '' + userInfo.risk_level
              self.visitProdType = 2
              return false
            else
              self.visitProdType = 3
              self.isShowRisk = true

        # 投资期限和投资品种是否匹配的处理
        if 'false' is '' + prodObj?.tzpp
          # 投资期限的处理
          if userInfo?.tzqx < prodObj?.tzqxlx
            self.visitProdType = 3
            self.isShowTzqx = true
          else
            self.isShowTzqx = false

          # 投资品种的处理
          if userInfo?.tzpz < prodObj?.tzpz
            self.visitProdType = 3
            self.isShowTzpz = true
          else
            self.isShowTzpz = false

      # 日期格式转换 YY-MM-DD
      changeDate: (dateStr) ->
        tmp_year = dateStr?.substring 0, 4
        tmp_month = dateStr?.substring 4, dateStr.length - 2
        tmp_day = dateStr?.substring dateStr?.length - 2
        tmpDate = tmp_year + tmp_month + tmp_day
        return tmpDate

      # 获取产品详情
      getProductDetail: () ->
        self = @
        id = self.$route.params.id

        # 查询产品详情参数
        params =
          product_id: id

        return product_detail_api.getProductDetail params
          .then (res) ->
            # 获取session中的用户信息 --- 风险测评三要素
            userInfo = sessionStorage.getItem 'userInfo'
            self.userInfo = JSON.parse userInfo

            # 用于风险等级匹配的产品信息
            self.prodObj = res?.body[0]

            if 'false' is '' + res?.body[0]?.ykpp
              # 检查是否登录
              product_detail_api.getUserSession()
                .then (result) ->
                  if 200 is result?.status
                    self.prodInfoShow self.userInfo, self.prodObj

                .catch (err) ->
                  if 403 is err?.status
                    self.$router.push {path: '/login'}
                    return false

            self.product_xq = res?.body

            # 转换日期格式成 YY-MM-DD
            for prodInfo in self.product_xq
              self.prodInfo = prodInfo

            # _.forIn self.prodInfo, (value, key) ->
            #   if !value
            #     self.prodInfo.key = '-'

            self.prodInfo.prod_statu = self.getProdStatu self.prodInfo.sub_begin_date, self.prodInfo.sub_end_date, self.prodInfo.pur_begin_date, self.prodInfo.pur_begin_date, self.prodInfo.came_date

          .catch (err) ->
            console.log err

      # 获取净值列表
      getNetList: (code) ->
        self = @
        pageNum = parseInt(self.pageNet) or 1

        # 查询产品净值列表参数
        params =
          pageNum: pageNum
          pageSize: 10
          query:
            prod_code: code

        return product_detail_api.getNetList params
          .then (res) ->
            # 分页
            if self.prodNet.length == 0
              if res?.data?.data?.length != 0
                # 隐藏“暂无数据”提示
                self.isShowNet = false
                self.prodNet = res?.body?.data
              else
                # 显示“暂无数据”提示
                self.isShowNet = true
                # self.viewMoreNet='已显示全部内容'
            else
              # 隐藏“暂无数据”提示
              self.isShowNet = false
              if res?.body?.data?.length != 0
                for item in res?.body?.data
                  self.prodNet.push item
              else
                self.viewMoreNet ='已显示全部内容'

            self.pageNet = res?.body?.pageNum

          .catch (err) ->
            console.log err

      # 获取公告列表
      getNoticeList: (code) ->
        self = @
        pageNum = parseInt(self.pageNotice) or 1

        # 查询公告列表参数
        params =
          pageNum: pageNum
          pageSize: 10
          query:
            prod_code: code

        return product_detail_api.getNoticeList params
          .then (res) ->
            # 分页
            if self.notices.length == 0
              if res?.data?.data?.length != 0
                # 隐藏“暂无数据”提示
                self.isShowNotice = false
                self.notices = res?.body?.data
              else
                # 显示“暂无数据”提示
                self.isShowNotice = true
                # self.viewMoreNotice='已显示全部内容'
            else
              # 隐藏“暂无数据”提示
              self.isShowNotice = false

              if res?.body?.data?.length != 0
                for item in res?.body?.data
                  self.notices.push item
              else
                self.viewMoreNotice ='已显示全部内容'

            self.pageNotice = res?.body?.pageNum

            # 将发布时间日期格式转成YY-MM-DD
            for notice in self.notices
              notice.updated_at = notice.updated_at.substring 0, 10

          .catch (err) ->
            console.log err

      # 获取法律文件的列表
      getLawList: (code) ->
        self = @
        pageNum = parseInt(self.pageLaw) or 1

        # 查询法律文件的参数
        params =
          pageNum: pageNum
          pageSize: 10
          conditions: "prod_code:#{code}"

        return product_detail_api.getLawList params
          .then (res) ->

            # 法律文件的分页
            if self.prodLaw.length == 0
              if res?.body?.table_data?.length != 0
                # 隐藏“暂无数据”提示
                self.isShowLaw = false
                self.prodLaw = res?.body?.table_data
              else
                # 显示“暂无数据”提示
                self.isShowLaw = true
                # self.viewMoreLaw='已显示全部内容'
            else
              # 隐藏“暂无数据”提示
              self.isShowLaw = false

              if res?.body?.table_data?.length != 0
                for item in res?.body?.table_data
                  self.prodLaw.push item
              else
                self.viewMoreLaw ='已显示全部内容'

            self.pageLaw = pageNum++

            # 将发布时间日期格式转成YY-MM-DD
            for law in self.prodLaw
              law.operator_date = law.operator_date?.substring 0, 10

          .catch (err) ->
            console.log err

      # 公告详情页跳转
      goNoticeDetail: (detail_id) ->
        self = @
        self.$router.push {name:'notice_detail', params: {'type': 'gg', 'detail_id': detail_id} }

      # 法律文件详情页跳转
      goLawDetail: (detail_id) ->
        self = @
        self.$router.push {name:'notice_detail', params: {'type': 'law', 'detail_id': detail_id} }

      # 设置菜单剩余部分的宽度
      setTabRightWidth: () ->
        self = @
        liW = self.getLisWidth()
        self.tabUlWidth = $('.c-tab-nav ul').css('width')
        self.tabUlWidth = self.tabUlWidth?.substring(0, self.tabUlWidth.indexOf('p'))
        $('.c-tab-nav ul .c-tab-right').css('width', self.tabUlWidth-liW + 'px')

      # 获取菜单中全部li的宽度
      getLisWidth: () ->
        self = @
        lis = $(".c-tab-nav").children("ul").children("li")
        w = 0
        for i in lis
          # 获取div盒子模型宽度 不带单位
          liWidth = i.getBoundingClientRect().width
          w += liWidth
        return w

      # 点击购买
      purchase: () ->
        self = @
        tempObj = JSON.stringify self.product 
        localStorage.setItem 'payInfo', tempObj
        self.$router.push {path: '/pay'}

      # 判断产品状态
      getProdStatu:(d1, d2, d3, d4, d5)->

        # 产品状态
        prodStatu = ''

        # 获取当前日期
        curdate = new Date()
        y = curdate.getFullYear()
        m = curdate.getMonth() + 1
        d = curdate.getDate()
        if m < 10
          m = '0' + m
        d0 = y + '-' + m + '-' + d

        # 将字符串日期转换为可比较
        time0 = new Date(d0?.replace("-", "/").replace("-", "/"));
        time1 = new Date(d1?.replace("-", "/").replace("-", "/"));
        time2 = new Date(d2?.replace("-", "/").replace("-", "/"));
        time3 = new Date(d3?.replace("-", "/").replace("-", "/"));
        time4 = new Date(d4?.replace("-", "/").replace("-", "/"));
        time5 = new Date(d5?.replace("-", "/").replace("-", "/"));

        # 当前日期小于募集开始日期
        if time0 < time1
          prodStatu = '即将发售'
        # 当前日期在募集开始-募集结束，或者申购开始-申购结束期间
        else if (time0 > time1 && time0 < time2) || (time0 > time3 && time0 < time4)
          prodStatu = '正在发售'
        # 当结束日期为空
        else if '' is d5 or not d5
          prodStatu = '存续期'
        # 当前日期大于结束日期
        else if d0 > d5
          prodStatu = '已结束'
        # 其他情况
        else
          prodStatu = '存续期'

        return prodStatu

    # 监听
    watch:

      # 监听tab菜单切换，设置th的值
      tabNavSta: () ->
        self = @
        self.tdWArr = []
        if 1 is self.tabNavSta
          setTimeout (->
            self.tdWArr.push $('#c-tab-body tr td:nth-child(1)').css('width')
            self.tdWArr.push $('#c-tab-body tr td:nth-child(2)').css('width')
            self.tdWArr.push $('#c-tab-body tr td:nth-child(3)').css('width')
            self.tdWArr.push $('#c-tab-body tr td:nth-child(4)').css('width')

            $('#net_tab .c-th:nth-child(1)').css('width', self.tdWArr[0])
            $('#net_tab .c-th:nth-child(2)').css('width', self.tdWArr[1])
            $('#net_tab .c-th:nth-child(3)').css('width', self.tdWArr[2])
            $('#net_tab .c-th:nth-child(4)').css('width', self.tdWArr[3])
          ), 10

      # 监听 屏幕宽度的变化，设置tab菜单剩余的宽度
      screenWidth: () ->
        self = @
        if !self.timer
          self.setTabRightWidth()
          self.timer = true
          setTimeout (->
            self.timer = false
          ), 10

    beforeRouteLeave: (to, from, next) ->
      fixedDestroy()
      return next()

    # 计算属性
    computed:
      # 加载中的样式
      loaddingClass: () ->
        self = @
        if self.loadedSucc
          return 'c-hidden'
        if self.loadedFail
          return 'c-hidden'
        return ''

      # 加载成功的样式
      loadedSuccClass: () ->
        self = @
        return if self.loadedSucc then '' else 'c-vhidden'

      # 加载失败的样式
      loadedFailClass: () ->
        self = @
        return if self.loadedFail then '' else 'c-hidden'

    # 初始化
    mounted: () ->
      self = @

      # 查询产品详情
      self.getProductDetail()
        .then (res) ->

          # 获取产品净值
          self.gotoPage self.prodInfo.prod_code, self.pageNet, 0

          # 获取公告列表
          self.gotoPage self.prodInfo.prod_code, self.pageNotice, 1

          # 获取法律文件列表
          self.gotoPage self.prodInfo.prod_code, self.pageLaw, 2

          # 固定头部插件
          fixedTop
            elem_id: 'net_tab'
            mgt_top: 612

          # 加载成功 - 处理函数
          self.loadedSuccFunc()

        .catch (err) ->
          console.log 'err:', err

      # 设置净值表头宽度
      self.setTabRightWidth()

      # 获取屏幕宽度
      window.onresize = () ->
        return (()->
          window.screenWidth = document.body.clientWidth
          self.screenWidth = window.screenWidth
        )()